package com.mdxq.mall.config;

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

@Configuration
@EnableCaching //spring开启数据缓存的开关
public class RedisConfig {
    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory factory){
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofMinutes(10))//缓存默认十分钟过期时间
                //设置键的序列化方式StringRedisSerializer，会将key以utf-8的编码为字节数据，适用于redis的键为字符串的情况
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                //设置值的序列化方式，委托jackson框架来完成序列化，以json格式序列化
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
        return RedisCacheManager.builder(factory).build();
    }
    @Bean //redis连接工厂
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory){
        RedisTemplate<String,Object> template = new RedisTemplate<>();//实例化一个redis模板实例
        template.setConnectionFactory(factory);//建立redis连接，工厂模式

        //设置键的序列化方式
        template.setKeySerializer(new StringRedisSerializer());
        //设置值的序列化方式（委托jackson框架来完成序列化，默认转换成json格式存储）
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        //设置哈希键序列化方式
        template.setHashKeySerializer(new StringRedisSerializer());
        //设置哈希值序列化方式
        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());

        template.afterPropertiesSet();
        return template;//返回设置完成的模板实例
    }
}
